package com.baicaixiaozhan.springsecurityswaggerdemo.config;

import com.baicaixiaozhan.springsecurityswaggerdemo.service.impl.ApplicationUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import static com.baicaixiaozhan.springsecurityswaggerdemo.pojo.PersonPermission.ADMIN_TEST;
import static com.baicaixiaozhan.springsecurityswaggerdemo.pojo.PersonPermission.DEVELOPMENT_TEST;

/**
 * DESC: spring security 配置类
 *
 * @author : baicaixiaozhan
 * @since : 2020-11-04
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final ApplicationUserServiceImpl applicationUserService;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public SecurityConfig(ApplicationUserServiceImpl applicationUserService, PasswordEncoder passwordEncoder) {
        this.applicationUserService = applicationUserService;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        final DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(applicationUserService);
        return provider;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin().and()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-ui.html",
                        "/webjars/**",
                        "/v2/api-docs-ext",
                        "/v2/api-docs",
                        "/swagger-resources/**").hasAnyAuthority(
                                ADMIN_TEST.getPermission(), DEVELOPMENT_TEST.getPermission())
                .anyRequest()
                .authenticated();
    }
}

